﻿using Microsoft.EntityFrameworkCore;
using Store.IDAL;
using System;
using System.Threading.Tasks;

namespace Store.BLL
{
    public class UserManager : IBLL.IUserManager
    {
        private readonly IUserService _userService;

        public UserManager()
        {

        }

        public UserManager(IDAL.IUserService userService)
        {
            _userService = userService;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="oldPwd"></param>
        /// <param name="newPwd"></param>
        /// <returns></returns>
        public async Task ChangePassword(Guid Id, string oldPwd, string newPwd)
        {
            var IsExist = await _userService.GetAllAsync().AnyAsync(m => m.Id == Id && m.Password == oldPwd);
            if (IsExist)
            {
                var result = await _userService.GetOneById(Id);
                result.Password = newPwd;
                await _userService.EditAsync(result);
            }

        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public bool Login(string account, string password, out Guid userid)
        {
            var user = _userService.GetAllAsync().FirstOrDefaultAsync(m => m.LoginName == account && m.Password == password);
            user.Wait();
            var result = user.Result;
            if (result == null)
            {
                userid = new Guid();
                return false;
            }
            else
            {
                userid = result.Id;
                return true;
            }
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task Register(Models.User user)
        {
            if (await _userService.GetAllAsync().AnyAsync(m => m.LoginName == user.LoginName))
            {
                throw new ArgumentException("用户名已存在!");
            }
            await _userService.CreateAsync(user);
        }
    }
}
